<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>Spring生成bean的过程 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2017/11/17/Spring-create-bean/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Spring生成bean的过程</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-17T11:07:00+00:00">2017-11-17</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/11/17/Spring-create-bean/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/11/17/Spring-create-bean/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2017/11/17/Spring-create-bean/" class="leancloud_visitors" data-flag-title="Spring生成bean的过程">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>spring是java程序员的春天，很多人写完helloworld后就转入了spring的怀抱。现在来了解一下bean是怎么创建的吧。</p>
<a id="more"></a>

<p>这里假设你已经对java比较了解，类反射代理之类的也有所涉猎。否则建议先了解一下类的反射。</p>
<h2 id="如何定义Bean"><a href="#如何定义Bean" class="headerlink" title="如何定义Bean"></a>如何定义Bean</h2><p>假设你在写一个类Dog，Dog有年龄age，名字name，它还可以say。以下是实现代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dog</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> Integer age;</span><br><span class="line">    <span class="keyword">public</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"my name is "</span>+name+<span class="string">" . age is "</span>+age);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> Dog().say();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们来看看怎么描述我们想要创建的Dog。</p>
<h3 id="类名"><a href="#类名" class="headerlink" title="类名"></a>类名</h3><p>类名肯定得有，到时候通过<code>Class#forName()</code>方法可以加载到这个类。</p>
<h3 id="实例别名"><a href="#实例别名" class="headerlink" title="实例别名"></a>实例别名</h3><p>如果你不想通过类名来描述一个实例，又或是这个类有多个实例，这时候就需要一个实例别名来描述了。</p>
<h3 id="构造函数"><a href="#构造函数" class="headerlink" title="构造函数"></a>构造函数</h3><p>如果你希望通过向特定的构造函数传入入参来创建实例，那么你得描述到底使用哪个构造函数，简单的可以通过每个参数的类型，来判断。然而，如果你的入参是通过别的bean定义得来的，那你可得考虑两个实例的生成关系了。</p>
<h3 id="属性设置"><a href="#属性设置" class="headerlink" title="属性设置"></a>属性设置</h3><p>就像这个Dog类，不用向构造函数传参即可new出来，那如果想在实例生成后设置上属性该怎么做呢？是不是得标记一下你想给哪个属性设置什么值。</p>
<h3 id="初始化方法"><a href="#初始化方法" class="headerlink" title="初始化方法"></a>初始化方法</h3><p>你的实例生成了，属性也设置上了，你想让他试着叫一下，是不是得指定say方法在实例化后执行？</p>
<h3 id="销毁方法"><a href="#销毁方法" class="headerlink" title="销毁方法"></a>销毁方法</h3><p>假如你的Dog连接了一些资源，在下线时需要销毁，是不是得指定方法在系统执行完后执行？</p>
<p>其他方面，读者可以再考虑一下。</p>
<h2 id="BeanDefinition"><a href="#BeanDefinition" class="headerlink" title="BeanDefinition"></a>BeanDefinition</h2><p>在第一小节中，大家大致了解了对于一个对象该怎么描述。为什么需要考虑对象的描述呢？因为使用spring就会把对象的生成交给spring，spring需要知道对象该怎么生成。</p>
<p>在spring中，BeanDefinition就是描述对象的类。在getBean时，spring通过对BeanDefinition列表的扫描得知你需要哪一个bean，进而生成bean返回给你。</p>
<h3 id="通过代码生成BeanDefinition"><a href="#通过代码生成BeanDefinition" class="headerlink" title="通过代码生成BeanDefinition"></a>通过代码生成BeanDefinition</h3><p>最普通的情况就是通过xml生成了，spring通过对xml的读取解析得到用户写的bean配置，想一想第一小节中那些描述点都在spring的xml配置的哪些地方。</p>
<p>实际上也可以通过代码生成:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dog</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> Integer age;</span><br><span class="line">    <span class="keyword">public</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"my name is "</span>+name+<span class="string">" . age is "</span>+age);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAge</span><span class="params">(Integer age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> Dog().say();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 准备生成dog的定义</span></span><br><span class="line">        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(Dog<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="comment">// 设置它的属性</span></span><br><span class="line">        builder.addPropertyValue(<span class="string">"name"</span>,<span class="string">"john"</span>);</span><br><span class="line">        builder.addPropertyValue(<span class="string">"age"</span>,<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 生成beanFactory</span></span><br><span class="line">        DefaultListableBeanFactory beanFactory = <span class="keyword">new</span> DefaultListableBeanFactory();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 添加dog定义</span></span><br><span class="line">        beanFactory.registerBeanDefinition(<span class="string">"dog"</span>,builder.getBeanDefinition());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取dog</span></span><br><span class="line">        Dog dog = (Dog) beanFactory.getBean(<span class="string">"dog"</span>);</span><br><span class="line">        dog.say();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">my name is <span class="keyword">null</span> . age is <span class="keyword">null</span></span><br><span class="line">my name is john . age is <span class="number">1</span></span><br></pre></td></tr></table></figure>

<h3 id="通过xml生成BeanDefinition"><a href="#通过xml生成BeanDefinition" class="headerlink" title="通过xml生成BeanDefinition"></a>通过xml生成BeanDefinition</h3><p>xml生成BeanDefinition无非是原先用代码描述的BeanDefinition换成用xml描述，至于怎么读取xml，spring有自己的方法。而xml的解析技术一般分为两种 DOM SAX</p>
<h4 id="DOM方式"><a href="#DOM方式" class="headerlink" title="DOM方式"></a>DOM方式</h4><p>根据XML的层级结构在内存中分配一个树形结构,把XML的标签,属性和文本等元素都封装成树的节点对象</p>
<ul>
<li>优点: 便于实现增 删 改 查</li>
<li>缺点: XML文件过大可能造成内存溢出</li>
</ul>
<h4 id="SAX方式"><a href="#SAX方式" class="headerlink" title="SAX方式"></a>SAX方式</h4><p>采用事件驱动模型边读边解析:从上到下一行行解析,解析到某一元素, 调用相应解析方法</p>
<ul>
<li>优点: 不会造成内存溢出,</li>
<li>缺点: 查询不方便,但不能实现 增 删 改</li>
</ul>
<p>具体如何解析这里就不深究了，重点是你可以从xml节点上读取相关信息生成BeanDefinition</p>
<h3 id="实际使用"><a href="#实际使用" class="headerlink" title="实际使用"></a>实际使用</h3><p>实际上，DefaultListableBeanFactory不具备从xml配置中获取BeanDefinition，它只能通过代码的方式注册。我们应用一般采用<code>ApplicationContext</code>的实现类<code>FileSystemXmlApplicationContext</code>,<code>ClassPathXmlApplicationContext</code>和<code>WebXmlApplicationContext</code>来从xml中获取BeanDefinition，并注册到自身的属性BeanFactory中。ClassPathXmlApplicationContext的类关系图如下:</p>
<p><img src="/images/pasted-90.png" alt="upload successful"></p>
<p>在生成<code>ClassPathXmlApplicationContext</code>对象时，构造函数入参会传入具体xml配置文件的位置，可以是单个，也可以是多个，也可以包含匹配符。</p>
<p>接着会调用<code>AbstractApplicationContext</code>的refresh方法。refresh方法中会调用自身方法obtainFreshBeanFactory来获取生成的Bean。</p>
<p>obtainFreshBeanFactory方法会调用<code>AbstractRefreshableApplicationContext</code>的refreshBeanFactory方法。这个方法的作用是销毁已有beanFactory中的bean，并且关闭beanFactory。接着会去生成一个DefaultListableBeanFactory对象，最后使用loadBeanDefinitions方法从xml配置中加载BeanDefinition。</p>
<p>实际上<code>AbstractXmlApplicationContext</code>实现了loadBeanDefinitions方法，在这个方法里，使用了XmlBeanDefinitionReader对象来读取xml配置信息并转换成BeanDefinition。XmlBeanDefinitionReader采用SAX方式读取xml。</p>
<h2 id="生成Bean对象"><a href="#生成Bean对象" class="headerlink" title="生成Bean对象"></a>生成Bean对象</h2><p>上边两个小节描述了Bean的定义，接下来就是重头了，如何生成Bean对象，spring又是如何让生成Bean对象变得可扩展。</p>
<h3 id="使用反射技术生成对象"><a href="#使用反射技术生成对象" class="headerlink" title="使用反射技术生成对象"></a>使用反射技术生成对象</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dog</span> </span>&#123;</span><br><span class="line">    <span class="keyword">protected</span> Integer age;</span><br><span class="line">    <span class="keyword">public</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">say</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"my name is "</span>+name+<span class="string">" . age is "</span>+age);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAge</span><span class="params">(Integer age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 获取Dog类</span></span><br><span class="line">            Class dogClass = Class.forName(<span class="string">"Dog"</span>);</span><br><span class="line">            <span class="comment">// 通过类生成对象</span></span><br><span class="line">            Dog dog1 = (Dog) dogClass.newInstance();</span><br><span class="line">            <span class="comment">// 获取特定的属性</span></span><br><span class="line">            Field field = dogClass.getField(<span class="string">"name"</span>);</span><br><span class="line">            <span class="comment">// 填充属性</span></span><br><span class="line">            field.set(dog1,<span class="string">"landa"</span>);</span><br><span class="line">            dog1.say();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InstantiationException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchFieldException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ClassNotFoundException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">my name is landa . age is null</span><br></pre></td></tr></table></figure>

<p>以上代码演示了如何不通过new的方式生成对象，并且给对象设置上属性值。可以说，spring做的一切都是基于java的反射。</p>
<h3 id="BeanFactory类图"><a href="#BeanFactory类图" class="headerlink" title="BeanFactory类图"></a>BeanFactory类图</h3><p><img src="/images/pasted-91.png" alt="upload successful"></p>
<h3 id="AbstractBeanFactory-doGetBean方法"><a href="#AbstractBeanFactory-doGetBean方法" class="headerlink" title="AbstractBeanFactory#doGetBean方法"></a>AbstractBeanFactory#doGetBean方法</h3><p>DefaultListableBeanFactory的getBean方法最终会调用AbstractBeanFactory的doGetBean方法。</p>
<p>doGetBean方法执行流程:</p>
<img src="http://www.plantuml.com/plantuml/svg/bLLDKzfG5DtdLxoLepFCk6yM7RNZJ3TreKit0P-Q3YPCIEsuKomOv4CwAigNIYkKMXMeYi4W_fdS9FoBldm25JhJB82yT-yvzvnxtuEYmY8ZY1Jr1XdfH-YUwCLpxUQxdl_YnmptWTd0DCNn8aO2kxOk8WgHPmsBIriXFCyByqn0v8MjMHAgPTlQtR69SP0rKxMJbjh9Gx7cua0y1ViN4nJcLf29Q54sTlMZ6i5RPBcr81Pv1mOQ9QD-h2ffLOwhyfNUEOIRKrM-wSFJ95jLAggSq4xh47rKdm-rXnszbZ0t82fv264NUS7_4GV4i8U2p4ZjTzb-0wa1iPINXHaXkBKuBjNYYALUPtfajZ4ixkSiSr2DQ6V5mPAyA0z9VOhvI6IZISACbrnlBmdIHIzt2VMsqIpxeDqY7aAqGa97baXJ5BkA9f5fIgRQBz1ADtr3KqXSnvmLWQOegv-a3myDqWGRWxJLxETxZWm65y1EGzeju-K82cSsqZBtb_UzRSNeVgKjEBS0ayuPaBSEBN9vaVCG7rtBdT0v9h2EXrhjEaTwfHNZ8EL8y02s8xBTigV4hW47mvYG4G-6o0OrE87S2hjg_gA6Klf2e7kbf-iW5K1vWanIbRVjzF6AjFq2x3r19mAoJ7lhOP4F3JCYZqINMgOWUAn0Ea8qa5E39YQGjNQRLzln3IP4B57bbBqvbfeuCuJbUVDQ-9YQI4Co4adeSzF3jJgZHJgXAoK22CM6RP7QBHaFsV-rnRfRWdXLz5RCPteQBIsyM_3Ml3lZNxszRS3piLq5HE_qEyKwBb89VYGWcRKtd7kD7jS9LntvJ16inC2H6I79lhvc_65H8BCuyqdaFxC2dcD2Z3-8P_iZIbYNkO206H7thqhzw5oJCWFLZ9O5wNCuIsYrCdGED2bhR4TxkGn8BIEv2uLxHu_FlYlC0Td9wqfC_zaQb4WvNvP2czT9r9kAYMw9rg-hfFT6TKThHaPfTe-FNVAhSbqxHFBNCCTpcrWGiJ09cLy1woNCyjmY5ZRP09uoNWf6EMayNskfRxGxTjOPjzVWicdSLtp34-Dei6QM-WC0">




<p>doGetBean方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">doGetBean</span><span class="params">( <span class="keyword">final</span> String name, <span class="keyword">final</span> Class&lt;T&gt; requiredType, <span class="keyword">final</span> Object[] args, <span class="keyword">boolean</span> typeCheckOnly)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> String beanName = transformedBeanName(name);</span><br><span class="line">    Object bean;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Eagerly check singleton cache for manually registered singletons.</span></span><br><span class="line">    Object sharedInstance = getSingleton(beanName);</span><br><span class="line">    <span class="keyword">if</span> (sharedInstance != <span class="keyword">null</span> &amp;&amp; args == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (isSingletonCurrentlyInCreation(beanName)) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Returning eagerly cached instance of singleton bean '"</span> + beanName +</span><br><span class="line">                        <span class="string">"' that is not fully initialized yet - a consequence of a circular reference"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                logger.debug(<span class="string">"Returning cached instance of singleton bean '"</span> + beanName + <span class="string">"'"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        bean = getObjectForBeanInstance(sharedInstance, name, beanName, <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// Fail if we're already creating this bean instance:</span></span><br><span class="line">        <span class="comment">// We're assumably within a circular reference.</span></span><br><span class="line">        <span class="keyword">if</span> (isPrototypeCurrentlyInCreation(beanName)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanCurrentlyInCreationException(beanName);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Check if bean definition exists in this factory.</span></span><br><span class="line">        BeanFactory parentBeanFactory = getParentBeanFactory();</span><br><span class="line">        <span class="keyword">if</span> (parentBeanFactory != <span class="keyword">null</span> &amp;&amp; !containsBeanDefinition(beanName)) &#123;</span><br><span class="line">            <span class="comment">// Not found -&gt; check parent.</span></span><br><span class="line">            String nameToLookup = originalBeanName(name);</span><br><span class="line">            <span class="keyword">if</span> (args != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// Delegation to parent with explicit args.</span></span><br><span class="line">                <span class="keyword">return</span> (T) parentBeanFactory.getBean(nameToLookup, args);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// No args -&gt; delegate to standard getBean method.</span></span><br><span class="line">                <span class="keyword">return</span> parentBeanFactory.getBean(nameToLookup, requiredType);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!typeCheckOnly) &#123;</span><br><span class="line">            markBeanAsCreated(beanName);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">final</span> RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);</span><br><span class="line">            checkMergedBeanDefinition(mbd, beanName, args);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Guarantee initialization of beans that the current bean depends on.</span></span><br><span class="line">            String[] dependsOn = mbd.getDependsOn();</span><br><span class="line">            <span class="keyword">if</span> (dependsOn != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (String dependsOnBean : dependsOn) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (isDependent(beanName, dependsOnBean)) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbd.getResourceDescription(), beanName,</span><br><span class="line">                                <span class="string">"Circular depends-on relationship between '"</span> + beanName + <span class="string">"' and '"</span> + dependsOnBean + <span class="string">"'"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    registerDependentBean(dependsOnBean, beanName);</span><br><span class="line">                    getBean(dependsOnBean);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Create bean instance.</span></span><br><span class="line">            <span class="keyword">if</span> (mbd.isSingleton()) &#123;</span><br><span class="line">                sharedInstance = getSingleton(beanName, <span class="keyword">new</span> ObjectFactory&lt;Object&gt;() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> Object <span class="title">getObject</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            <span class="keyword">return</span> createBean(beanName, mbd, args);</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">                            <span class="comment">// Explicitly remove instance from singleton cache: It might have been put there</span></span><br><span class="line">                            <span class="comment">// eagerly by the creation process, to allow for circular reference resolution.</span></span><br><span class="line">                            <span class="comment">// Also remove any beans that received a temporary reference to the bean.</span></span><br><span class="line">                            destroySingleton(beanName);</span><br><span class="line">                            <span class="keyword">throw</span> ex;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (mbd.isPrototype()) &#123;</span><br><span class="line">                <span class="comment">// It's a prototype -&gt; create a new instance.</span></span><br><span class="line">                Object prototypeInstance = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    beforePrototypeCreation(beanName);</span><br><span class="line">                    prototypeInstance = createBean(beanName, mbd, args);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">finally</span> &#123;</span><br><span class="line">                    afterPrototypeCreation(beanName);</span><br><span class="line">                &#125;</span><br><span class="line">                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                String scopeName = mbd.getScope();</span><br><span class="line">                <span class="keyword">final</span> Scope scope = <span class="keyword">this</span>.scopes.get(scopeName);</span><br><span class="line">                <span class="keyword">if</span> (scope == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"No Scope registered for scope name '"</span> + scopeName + <span class="string">"'"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Object scopedInstance = scope.get(beanName, <span class="keyword">new</span> ObjectFactory&lt;Object&gt;() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="function"><span class="keyword">public</span> Object <span class="title">getObject</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">                            beforePrototypeCreation(beanName);</span><br><span class="line">                            <span class="keyword">try</span> &#123;</span><br><span class="line">                                <span class="keyword">return</span> createBean(beanName, mbd, args);</span><br><span class="line">                            &#125;</span><br><span class="line">                            <span class="keyword">finally</span> &#123;</span><br><span class="line">                                afterPrototypeCreation(beanName);</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br><span class="line">                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">catch</span> (IllegalStateException ex) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(beanName,</span><br><span class="line">                            <span class="string">"Scope '"</span> + scopeName + <span class="string">"' is not active for the current thread; consider "</span> +</span><br><span class="line">                            <span class="string">"defining a scoped proxy for this bean if you intend to refer to it from a singleton"</span>,</span><br><span class="line">                            ex);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">            cleanupAfterBeanCreationFailure(beanName);</span><br><span class="line">            <span class="keyword">throw</span> ex;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Check if required type matches the type of the actual bean instance.</span></span><br><span class="line">    <span class="keyword">if</span> (requiredType != <span class="keyword">null</span> &amp;&amp; bean != <span class="keyword">null</span> &amp;&amp; !requiredType.isAssignableFrom(bean.getClass())) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> getTypeConverter().convertIfNecessary(bean, requiredType);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (TypeMismatchException ex) &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Failed to convert bean '"</span> + name + <span class="string">"' to required type ["</span> +</span><br><span class="line">                        ClassUtils.getQualifiedName(requiredType) + <span class="string">"]"</span>, ex);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> (T) bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AbstractAutowireCapableBeanFactory-createBean方法"><a href="#AbstractAutowireCapableBeanFactory-createBean方法" class="headerlink" title="AbstractAutowireCapableBeanFactory#createBean方法"></a>AbstractAutowireCapableBeanFactory#createBean方法</h3><p>createBean方法执行流程:</p>
<img src="http://www.plantuml.com/plantuml/svg/ZLBTJjim5BxFK_XoI6WFGA-0AswsFa1l0dL5fc1NjWVIhc3Q80mQggqWQA4C8Nw4H9E9JQG9eo_ZO-SnPYULsasQDj_Pvtm_vtnsk72PS9mvfBuELMkmZ5q2WwuSxiBdVNjvvQxXF7o4WoE8Xf1sTFV3ekzoNZ6GAiDDbs6qXiKghIEwZXdpwfY_h1I4kpVvnJx3dFhhU04tACDBnCWHuRd2eqGT3TN38SHdUNIeE-SgQ5kz6j7PoMzzynj6Oy6KgfIBAgChc7FAP7AdJbFvr8KmWw07MIgJJVCeiqlTteP1NpxlMOyokvB9dZgEuEEZ_Fb5_TZIjqK1dkzq6Cai_0yn5Lx1mQKXrM6ilsKr8fFxShpcfEsl8-hUTmZYSebsn4Bz-htgdyhaKpwAyz6EyJHUSX3BTDjspTO812UborBhNxPCD3KoPMY-8J1R8funutllfWmPwh6dKGTwVTXyaabB9Ybvw_l5pfAM7bpOdRMl9ydCmjbE2R2tryjly8emGJjU0xqOXrtEKuhy2KSpIAnYOdkF8pJZ87lcq8InKZnnGPiE9dMlCVb3TRh8i2kAN4hoQPHJG9nV">


<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createBean</span><span class="params">(String beanName, RootBeanDefinition mbd, Object[] args)</span> <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Creating instance of bean '"</span> + beanName + <span class="string">"'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    RootBeanDefinition mbdToUse = mbd;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Make sure bean class is actually resolved at this point, and</span></span><br><span class="line">    <span class="comment">// clone the bean definition in case of a dynamically resolved Class</span></span><br><span class="line">    <span class="comment">// which cannot be stored in the shared merged bean definition.</span></span><br><span class="line">    Class&lt;?&gt; resolvedClass = resolveBeanClass(mbd, beanName);</span><br><span class="line">    <span class="keyword">if</span> (resolvedClass != <span class="keyword">null</span> &amp;&amp; !mbd.hasBeanClass() &amp;&amp; mbd.getBeanClassName() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mbdToUse = <span class="keyword">new</span> RootBeanDefinition(mbd);</span><br><span class="line">        mbdToUse.setBeanClass(resolvedClass);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Prepare method overrides.</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        mbdToUse.prepareMethodOverrides();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(mbdToUse.getResourceDescription(),</span><br><span class="line">                beanName, <span class="string">"Validation of method overrides failed"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.</span></span><br><span class="line">        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);</span><br><span class="line">        <span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> bean;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbdToUse.getResourceDescription(), beanName,</span><br><span class="line">                <span class="string">"BeanPostProcessor before instantiation of bean failed"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Object beanInstance = doCreateBean(beanName, mbdToUse, args);</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Finished creating instance of bean '"</span> + beanName + <span class="string">"'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> beanInstance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AbstractAutowireCapableBeanFactory-doCreateBean方法"><a href="#AbstractAutowireCapableBeanFactory-doCreateBean方法" class="headerlink" title="AbstractAutowireCapableBeanFactory#doCreateBean方法"></a>AbstractAutowireCapableBeanFactory#doCreateBean方法</h3><p>doCreateBean方法执行流程:</p>
<img src="http://www.plantuml.com/plantuml/svg/VLHTJnf157tVNy4FyDKqgK_KsgHFDVNLbmMdTXlS9Rj3b3ujLH0g8asGA4LQgmBHy1NJ1eh2dvcPNVv5xyn5idxL1nBld3Ftd7lFhEPGtQQQzZBaTxUzKZDg4vsILqGttvfmP4Q9A0_4zQ5N-Y6onGZK5m3Bi-UYt1977TRVXr-UJldjll_hYd_zoTCNFDibkXrBhXZcUenGotmN-KIYr67zrjogoUjVHAsA5Dxj8ML1CorAGhQn_f5g8VZ3ibVPuSK2m6MhcmeR5jJXoWPeHdtKqAbXcU5DtLQgbos7BjjMb3YEPVDspIjqlTuGxb74TKANf3A9V4y-49lC3FhZNJ4yPtrtajgNDZLYheMaA3aRaMluf_cu5K_4fjD14Z-zukaqxzM4stXamHyVJtRp2041SaxLvjP63CR0snKso4btYghWaye1U4NunAr8FTTDlt76Rmvn4agLH49Tx1p0PTZ1g-u9jy06MGdENFFHfLVeiD69_xlyX0d3D61cCUDpq4RsX3VsUBwC-ttW0taeN4g-0oCt046zSWEB5Yp7JaGfxmputv9qZobgvUv9kX-JfQsuvIHimiztl6BcSIHKSA29Z9YQcrJJ6VYzKvZjfEhwzHHaa0tFW7styI1SRg3uZQUtfoHr56HW7Pkb_pm_Bpm9TfzTgiZiDlFa0q28t7_hI9H6qr3SKU5VL1AuIUHSDhp0FKyTZalyUmsfg8EtyrD_oj3SWmL9cVzh4Ox0glGe3IUejMdOP56Fwv6OSli6ofQT3CtFlu0-zpOt-mBmOXs5JKgkwAHc3noBF7iiLMNoyB1O_n8ne1y-Dgicknt35mUjl2OOc6VViYXSy8EpsOj-b0usseF6ivIkoVkiP32ZAfrughebiHAmvL0hhlq3">

<h4 id="循环依赖且带代理的情况"><a href="#循环依赖且带代理的情况" class="headerlink" title="循环依赖且带代理的情况"></a>循环依赖且带代理的情况</h4><p>注意其流程，这里举一个例子，C和D类循环依赖，且C和D类会被代理。</p>
<ol>
<li>先准备创建C，C实现类被称为元对象c</li>
<li>元对象c被放入被放入singletonFactories，且调用的是getEarlyBeanReference方法（这个方法比较<strong>凶残</strong>，会调用SmartInstantiationAwareBeanPostProcessor实现类的getEarlyBeanReference方法传入元返回新对象，AbstractAutoProxyCreator是该接口的实现类，他真正实现了生成代理）</li>
<li>执行populateBean方法给元对象c赋值</li>
<li><strong>好戏来了</strong>，这时候需要获取创建的D，元对象d也走上述方法。</li>
<li>到populateBean方法赋值时，doGetBean方法会把处在singletonFactories的对象c通过调用getEarlyBeanReference方法生成代理对象c，并且推到earlySingletonObjects中。</li>
<li>也就是说元对象d拿到的是代理对象c，但此时代理对象c中的元对象c里并没有d，如果在d初始化方法中调用c对象中的d的方法，那铁定报错。</li>
<li>调用元对象d的初始化方法</li>
<li>此时元对象d并没有在earlySingletonObjects中</li>
<li>注册元对象d回调，</li>
<li>正式生成单例对象d-&gt;调用getEarlyBeanReference方法生成代理对象d，并放入最终的singletonObjects中</li>
<li>元对象c的populate方法可以执行了，初始化方法也可以执行了。</li>
<li>此时元对象c在earlySingletonObjects中</li>
<li>正式生成单例对象c-&gt;调用getEarlyBeanReference方法生成代理对象c，并放入最终的singletonObjects中</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(<span class="keyword">final</span> String beanName, <span class="keyword">final</span> RootBeanDefinition mbd, <span class="keyword">final</span> Object[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Instantiate the bean.</span></span><br><span class="line">    BeanWrapper instanceWrapper = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (mbd.isSingleton()) &#123;</span><br><span class="line">        instanceWrapper = <span class="keyword">this</span>.factoryBeanInstanceCache.remove(beanName);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (instanceWrapper == <span class="keyword">null</span>) &#123;</span><br><span class="line">        instanceWrapper = createBeanInstance(beanName, mbd, args);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">final</span> Object bean = (instanceWrapper != <span class="keyword">null</span> ? instanceWrapper.getWrappedInstance() : <span class="keyword">null</span>);</span><br><span class="line">    Class&lt;?&gt; beanType = (instanceWrapper != <span class="keyword">null</span> ? instanceWrapper.getWrappedClass() : <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Allow post-processors to modify the merged bean definition.</span></span><br><span class="line">    <span class="keyword">synchronized</span> (mbd.postProcessingLock) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!mbd.postProcessed) &#123;</span><br><span class="line">            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);</span><br><span class="line">            mbd.postProcessed = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Eagerly cache singletons to be able to resolve circular references</span></span><br><span class="line">    <span class="comment">// even when triggered by lifecycle interfaces like BeanFactoryAware.</span></span><br><span class="line">    <span class="keyword">boolean</span> earlySingletonExposure = (mbd.isSingleton() &amp;&amp; <span class="keyword">this</span>.allowCircularReferences &amp;&amp;</span><br><span class="line">            isSingletonCurrentlyInCreation(beanName));</span><br><span class="line">    <span class="keyword">if</span> (earlySingletonExposure) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Eagerly caching bean '"</span> + beanName +</span><br><span class="line">                    <span class="string">"' to allow for resolving potential circular references"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        addSingletonFactory(beanName, <span class="keyword">new</span> ObjectFactory&lt;Object&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Object <span class="title">getObject</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> getEarlyBeanReference(beanName, mbd, bean);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Initialize the bean instance.</span></span><br><span class="line">    Object exposedObject = bean;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        populateBean(beanName, mbd, instanceWrapper);</span><br><span class="line">        <span class="keyword">if</span> (exposedObject != <span class="keyword">null</span>) &#123;</span><br><span class="line">            exposedObject = initializeBean(beanName, exposedObject, mbd);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">        <span class="keyword">if</span> (ex <span class="keyword">instanceof</span> BeanCreationException &amp;&amp; beanName.equals(((BeanCreationException) ex).getBeanName())) &#123;</span><br><span class="line">            <span class="keyword">throw</span> (BeanCreationException) ex;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbd.getResourceDescription(), beanName, <span class="string">"Initialization of bean failed"</span>, ex);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (earlySingletonExposure) &#123;</span><br><span class="line">        Object earlySingletonReference = getSingleton(beanName, <span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">if</span> (earlySingletonReference != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (exposedObject == bean) &#123;</span><br><span class="line">                exposedObject = earlySingletonReference;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (!<span class="keyword">this</span>.allowRawInjectionDespiteWrapping &amp;&amp; hasDependentBean(beanName)) &#123;</span><br><span class="line">                String[] dependentBeans = getDependentBeans(beanName);</span><br><span class="line">                Set&lt;String&gt; actualDependentBeans = <span class="keyword">new</span> LinkedHashSet&lt;String&gt;(dependentBeans.length);</span><br><span class="line">                <span class="keyword">for</span> (String dependentBean : dependentBeans) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) &#123;</span><br><span class="line">                        actualDependentBeans.add(dependentBean);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (!actualDependentBeans.isEmpty()) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> BeanCurrentlyInCreationException(beanName,</span><br><span class="line">                            <span class="string">"Bean with name '"</span> + beanName + <span class="string">"' has been injected into other beans ["</span> +</span><br><span class="line">                            StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +</span><br><span class="line">                            <span class="string">"] in its raw version as part of a circular reference, but has eventually been "</span> +</span><br><span class="line">                            <span class="string">"wrapped. This means that said other beans do not use the final version of the "</span> +</span><br><span class="line">                            <span class="string">"bean. This is often the result of over-eager type matching - consider using "</span> +</span><br><span class="line">                            <span class="string">"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Register bean as disposable.</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        registerDisposableBeanIfNecessary(beanName, bean, mbd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbd.getResourceDescription(), beanName, <span class="string">"Invalid destruction signature"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> exposedObject;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AbstractAutowireCapableBeanFactory-createBeanInstance方法"><a href="#AbstractAutowireCapableBeanFactory-createBeanInstance方法" class="headerlink" title="AbstractAutowireCapableBeanFactory#createBeanInstance方法"></a>AbstractAutowireCapableBeanFactory#createBeanInstance方法</h3><p>createBeanInstance方法执行流程</p>
<img src="http://www.plantuml.com/plantuml/svg/JL5DJy904BtlhzYZ_0KuAISlXiI3vvKkqWIsP7U9rmP1IiAN1eXWH1A3KG-rnXY-DFuPTjl-2wUK87EQcSnxysOU4f9mYL0Iwyb2jznpIjW9AL9rsunIvOxMYqRGdgdEGBdZS5XJphrQBVsFLRf0X4WXPERm0TRZQcXFz62XF_kgDbMTodg-z5-NM3i3l6kmSg604rZcAOimT-zG80oHn66zxlTUVDTMhJxGgE-EttlKJZSIaKAq82WWLFSP9xO0tRm9xORgEg5TyKVLVG7xo6WOCqjIpCsBl8nhYC2xWdsdHJZ-cC4Fc3I9D2rsU4auFG9enX8omwqi5SBYEnZym6zxS3siDAYal6WocYRCC0qYQTe2AbxEIekBMCh_liqBWz_XUluMAOifOjMg_gFxNZnAcR6HYo0nSv4l83C2d75IAb6klEkj6uu711kFchNWgHPypVJ35FmGqYgXFm00">

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> BeanWrapper <span class="title">createBeanInstance</span><span class="params">(String beanName, RootBeanDefinition mbd, Object[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Make sure bean class is actually resolved at this point.</span></span><br><span class="line">    Class&lt;?&gt; beanClass = resolveBeanClass(mbd, beanName);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (beanClass != <span class="keyword">null</span> &amp;&amp; !Modifier.isPublic(beanClass.getModifiers()) &amp;&amp; !mbd.isNonPublicAccessAllowed()) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(mbd.getResourceDescription(), beanName,</span><br><span class="line">                <span class="string">"Bean class isn't public, and non-public access not allowed: "</span> + beanClass.getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mbd.getFactoryMethodName() != <span class="keyword">null</span>)  &#123;</span><br><span class="line">        <span class="keyword">return</span> instantiateUsingFactoryMethod(beanName, mbd, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Shortcut when re-creating the same bean...</span></span><br><span class="line">    <span class="keyword">boolean</span> resolved = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">boolean</span> autowireNecessary = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (args == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (mbd.constructorArgumentLock) &#123;</span><br><span class="line">            <span class="keyword">if</span> (mbd.resolvedConstructorOrFactoryMethod != <span class="keyword">null</span>) &#123;</span><br><span class="line">                resolved = <span class="keyword">true</span>;</span><br><span class="line">                autowireNecessary = mbd.constructorArgumentsResolved;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (resolved) &#123;</span><br><span class="line">        <span class="keyword">if</span> (autowireNecessary) &#123;</span><br><span class="line">            <span class="keyword">return</span> autowireConstructor(beanName, mbd, <span class="keyword">null</span>, <span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> instantiateBean(beanName, mbd);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Need to determine the constructor...</span></span><br><span class="line">    Constructor&lt;?&gt;[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);</span><br><span class="line">    <span class="keyword">if</span> (ctors != <span class="keyword">null</span> ||</span><br><span class="line">            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||</span><br><span class="line">            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  &#123;</span><br><span class="line">        <span class="keyword">return</span> autowireConstructor(beanName, mbd, ctors, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// No special handling: simply use no-arg constructor.</span></span><br><span class="line">    <span class="keyword">return</span> instantiateBean(beanName, mbd);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AbstractAutowireCapableBeanFactory-populateBean方法"><a href="#AbstractAutowireCapableBeanFactory-populateBean方法" class="headerlink" title="AbstractAutowireCapableBeanFactory#populateBean方法"></a>AbstractAutowireCapableBeanFactory#populateBean方法</h3><p>populateBean方法执行流程:</p>
<p><img src="http://www.plantuml.com/plantuml/png/hP7FJi904CRl-nHz3hrGFNaZ73nnMM759krktTq6kPbW3mJH2nf2bCGG0XShXCHO_-ZBTBVrBLnOhD4rHXDxQ3kpCx_vvji2uv3om7F1yWU0DIkRDjFkP0kh1EOEv0x1TXrIj84WBXB6YvHK46E4YcYGdapJsKFQFofZ_-F8tkM8VWB8yrZEpyeuUObaDzvH917raxYr3Z3XoA9EROy3Q_M8YmdpgODhiZNEhevNxzwpU3nLapHApYSY78bM9-_IPLy7975R2qpksx8PvjLsm4dTeQXgOwLWgT7OJ_PkH7YRRmaGhbeBkVzZalhuYFB6DdG3nDuDMkqr6yZ3iM7E9l4yWdzGlAnIkkJbI8CA9SH8G2j8XTbugBdWjmQOkBpBu9NGVl1dtAB9e9asGzzt6z_vfUzSzsN3y3Ni69xfj39VtUQ1voPtrulmAL8POnxZn0S55GUU-mO0" alt></p>
<img src="http://www.plantuml.com/plantuml/svg/hP9FJy8m5CVl_HJx77fnUl96E7ZYCg7Y4jREjWjoCy4T5aGlQ1QY98OGk3WW9CRvyykitVmM5WepM4qqiOSsVNtlyxxlkm7ABC80s32oIJFjZ7QH321cMyp6oAnR16v32nKmPGM2ov1IJ7ZKIyydwVGfxPwMaFlvP1umIDO0uYeMiyiIIjuYqOdt9Ob7tIGEDW7231h4hXuoO2mNlnvHbzYeAe9XTdkstCDN_dmXEocKc8suF-11EwzIQLyR975B2KmUMwBfvzccnt3T9h1Y8gbWeL6RJuHZxj_dKmA8AiPSxl-O90yN4jROiseUf2k3bdDDU-9ag9cpWnr7zlbPyI9BwX8t0mNQAaAAFLA6yfeD-ueBVck0ZikhD5uH7db_ngsArcYwpPRhrXhV-QM-kQhB-lwxtzOyK-7vVnEEZvrQyd0tlxv4CgBremoxu0C0">

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">populateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, BeanWrapper bw)</span> </span>&#123;</span><br><span class="line">    PropertyValues pvs = mbd.getPropertyValues();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (bw == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!pvs.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">                    mbd.getResourceDescription(), beanName, <span class="string">"Cannot apply property values to null instance"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Skip property population phase for null instance.</span></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the</span></span><br><span class="line">    <span class="comment">// state of the bean before properties are set. This can be used, for example,</span></span><br><span class="line">    <span class="comment">// to support styles of field injection.</span></span><br><span class="line">    <span class="keyword">boolean</span> continueWithPropertyPopulation = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;</span><br><span class="line">        <span class="keyword">for</span> (BeanPostProcessor bp : getBeanPostProcessors()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (bp <span class="keyword">instanceof</span> InstantiationAwareBeanPostProcessor) &#123;</span><br><span class="line">                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;</span><br><span class="line">                <span class="keyword">if</span> (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) &#123;</span><br><span class="line">                    continueWithPropertyPopulation = <span class="keyword">false</span>;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!continueWithPropertyPopulation) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||</span><br><span class="line">            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) &#123;</span><br><span class="line">        MutablePropertyValues newPvs = <span class="keyword">new</span> MutablePropertyValues(pvs);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Add property values based on autowire by name if applicable.</span></span><br><span class="line">        <span class="keyword">if</span> (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) &#123;</span><br><span class="line">            autowireByName(beanName, mbd, bw, newPvs);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Add property values based on autowire by type if applicable.</span></span><br><span class="line">        <span class="keyword">if</span> (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) &#123;</span><br><span class="line">            autowireByType(beanName, mbd, bw, newPvs);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        pvs = newPvs;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">boolean</span> hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();</span><br><span class="line">    <span class="keyword">boolean</span> needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (hasInstAwareBpps || needsDepCheck) &#123;</span><br><span class="line">        PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);</span><br><span class="line">        <span class="keyword">if</span> (hasInstAwareBpps) &#123;</span><br><span class="line">            <span class="keyword">for</span> (BeanPostProcessor bp : getBeanPostProcessors()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (bp <span class="keyword">instanceof</span> InstantiationAwareBeanPostProcessor) &#123;</span><br><span class="line">                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;</span><br><span class="line">                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);</span><br><span class="line">                    <span class="keyword">if</span> (pvs == <span class="keyword">null</span>) &#123;</span><br><span class="line">                        <span class="keyword">return</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (needsDepCheck) &#123;</span><br><span class="line">            checkDependencies(beanName, mbd, filteredPds, pvs);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    applyPropertyValues(beanName, mbd, bw, pvs);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="AbstractAutowireCapableBeanFactory-initializeBean方法"><a href="#AbstractAutowireCapableBeanFactory-initializeBean方法" class="headerlink" title="AbstractAutowireCapableBeanFactory#initializeBean方法"></a>AbstractAutowireCapableBeanFactory#initializeBean方法</h3><p>initializeBean方法执行流程:</p>
<img src="http://www.plantuml.com/plantuml/svg/xLBRJjim6BxFK_G1U0Au0WGIqeQGk4L2Xlw0jM17jja6LwWh5KpG0EhAeLqrDWuLYAK8iGNAu6LY9uynEsvBGPk6nEroPVs_yvtyELmW9XodDwFMJfA3TKpUqZVG_munU0rYZcQvAb-hoqzz3g42CWpFpWadepzvd5ErwXGW8h_Nuc8ZkYcaym4z6KNp5g8p6NGHvwyeoW9xl1X6quAonOUXNDsJcri6LrtMvSfHN0dbJKa6ryd5WGCacp4wZDwayI4krGt66ELYZD5fu9mogoQ-QCRx-GdYFQm6O8Oo625OOEJY9IGm9N_nffbLta-FoVrU59xQUrgDz7DgvqVgUdjzgcNLwlQ3g7cKt9TafQRA3Srkrkag-bLGkq6FJSm2flvsW-JhcRmxZOj1TFSvkIhhdonMjGw8kOlZcCow82WPUg-DB32GX_buin25vrrF8FqjRTYZteAB1BHujJhSTWecezOy2ZUYS5bz-Mc5tUwhZnLvcvDX-8TiRHTCOi-fGgS6dOYrUaEjYZgsRsr2MMnQT3GZWEctyO0937mSX8NlWbJLDUDYSZwbxrxhalWRif5l2trwwIL5wJV2_lVatptXWdhERm00">

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">initializeBean</span><span class="params">(<span class="keyword">final</span> String beanName, <span class="keyword">final</span> Object bean, RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (System.getSecurityManager() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        AccessController.doPrivileged(<span class="keyword">new</span> PrivilegedAction&lt;Object&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Object <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                invokeAwareMethods(beanName, bean);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, getAccessControlContext());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        invokeAwareMethods(beanName, bean);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Object wrappedBean = bean;</span><br><span class="line">    <span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123;</span><br><span class="line">        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        invokeInitMethods(beanName, wrappedBean, mbd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(</span><br><span class="line">                (mbd != <span class="keyword">null</span> ? mbd.getResourceDescription() : <span class="keyword">null</span>),</span><br><span class="line">                beanName, <span class="string">"Invocation of init method failed"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123;</span><br><span class="line">        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> wrappedBean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><img src="http://www.plantuml.com/plantuml/svg/hLDTRn9157tVNx7_mFVsgINHzCac93wHc2bxIzSiCsHsYDQdROjAJGeyG5Mis4hwaPYo41ALeF9dTcQNV-7i3CW2ZHBZlcmozzvpppdtNcFDp07R18J5wK3q6-k6iMPQvC7I6-z-YFn6CAouDiuvm0Y-ZxACK1lSUu2eiv-UlZ_SUG9PvWRVRgFALruzNJSmOM1IExV735D-goAeP0aJDalS7qIz2_wpBCwEUTMFZdw8jtxqwNCmR8UrbpB106oPSP-OQvO2Od2dWB7NZ4QlCdWBkmnXPYDc4xpn556LlarSjar95boNK8cQmONPooRi4WfpXHe-WyFwHr6kxKW4FlWITO_2-aq6_nLmOvS1tSAs17Fivmb0pRTsnSllD9X5KdT9ckdKhB8m3IuuBbgbiNUkWx63BovvzL15D7uwZoXRpH9LPO5adhSnf12sR4kII15PJOlnF5tTHm-VryfZxr3M9IaiStfpdk0KTZn-qj2UpisrG0f5Py661QLQpmfIUASLLhfXRpZLj3oOfK7hXHnrH7sWPjrf1eDZkQ3AqZxljOHtBVetKee43KONui3_VwJahm2KxJz2JX4c7kjysJAwRkl6gkfPtebl9i5dpaPxkd9_Cb8H51Kvb2JoxssLfwgALGAA_PhmazUS1ZOPwwoGLqzujwIDYFi_pWFR8rR2Lntxbpaj7z2SNFuwNgvntHF-0N_VadtKyOZRDlzUdLskV7GPAHY_0000">
      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2017/11/17/Spring-create-bean/" title="Spring生成bean的过程">http://blog.gavinzh.com/2017/11/17/Spring-create-bean/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/25/Mybatis_SQL_java_instance_relation/" rel="next" title="Mybatis中SQL和Java类实例之间是怎么关联上的?">
                <i class="fa fa-chevron-left"></i> Mybatis中SQL和Java类实例之间是怎么关联上的?
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/20/spring-develop-summary/" rel="prev" title="Spring扩展点总结">
                Spring扩展点总结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#如何定义Bean"><span class="nav-number">1.</span> <span class="nav-text">如何定义Bean</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#类名"><span class="nav-number">1.1.</span> <span class="nav-text">类名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例别名"><span class="nav-number">1.2.</span> <span class="nav-text">实例别名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造函数"><span class="nav-number">1.3.</span> <span class="nav-text">构造函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#属性设置"><span class="nav-number">1.4.</span> <span class="nav-text">属性设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#初始化方法"><span class="nav-number">1.5.</span> <span class="nav-text">初始化方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#销毁方法"><span class="nav-number">1.6.</span> <span class="nav-text">销毁方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#BeanDefinition"><span class="nav-number">2.</span> <span class="nav-text">BeanDefinition</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#通过代码生成BeanDefinition"><span class="nav-number">2.1.</span> <span class="nav-text">通过代码生成BeanDefinition</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过xml生成BeanDefinition"><span class="nav-number">2.2.</span> <span class="nav-text">通过xml生成BeanDefinition</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#DOM方式"><span class="nav-number">2.2.1.</span> <span class="nav-text">DOM方式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SAX方式"><span class="nav-number">2.2.2.</span> <span class="nav-text">SAX方式</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实际使用"><span class="nav-number">2.3.</span> <span class="nav-text">实际使用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生成Bean对象"><span class="nav-number">3.</span> <span class="nav-text">生成Bean对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用反射技术生成对象"><span class="nav-number">3.1.</span> <span class="nav-text">使用反射技术生成对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#BeanFactory类图"><span class="nav-number">3.2.</span> <span class="nav-text">BeanFactory类图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbstractBeanFactory-doGetBean方法"><span class="nav-number">3.3.</span> <span class="nav-text">AbstractBeanFactory#doGetBean方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbstractAutowireCapableBeanFactory-createBean方法"><span class="nav-number">3.4.</span> <span class="nav-text">AbstractAutowireCapableBeanFactory#createBean方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbstractAutowireCapableBeanFactory-doCreateBean方法"><span class="nav-number">3.5.</span> <span class="nav-text">AbstractAutowireCapableBeanFactory#doCreateBean方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#循环依赖且带代理的情况"><span class="nav-number">3.5.1.</span> <span class="nav-text">循环依赖且带代理的情况</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbstractAutowireCapableBeanFactory-createBeanInstance方法"><span class="nav-number">3.6.</span> <span class="nav-text">AbstractAutowireCapableBeanFactory#createBeanInstance方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbstractAutowireCapableBeanFactory-populateBean方法"><span class="nav-number">3.7.</span> <span class="nav-text">AbstractAutowireCapableBeanFactory#populateBean方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbstractAutowireCapableBeanFactory-initializeBean方法"><span class="nav-number">3.8.</span> <span class="nav-text">AbstractAutowireCapableBeanFactory#initializeBean方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小结"><span class="nav-number">3.9.</span> <span class="nav-text">小结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2017/11/17/Spring-create-bean/';
          this.page.identifier = '2017/11/17/Spring-create-bean/';
          this.page.title = 'Spring生成bean的过程';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
